package com.aiwei.tdjk.service.impl;

import com.aiwei.tdjk.bean.Pager;
import com.aiwei.tdjk.dao.extend.GroupRelationExtendMapper;
import com.aiwei.tdjk.dto.request.GetGroupRelationPagerRequest;
import com.aiwei.tdjk.entity.GroupRelation;
import com.aiwei.tdjk.entity.GroupRelationExample;
import com.aiwei.tdjk.service.GroupRelationService;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * Created by yanfeng on 2016/12/13.
 */
@Service
public class GroupRelationServiceImpl implements GroupRelationService {

    @Autowired
    private GroupRelationExtendMapper groupRelationExtendMapper;

    /**
     * 新增
     *
     * @param groupRelation
     */
    @Override
    public void save(GroupRelation groupRelation) {
        groupRelationExtendMapper.insertSelective(groupRelation);
    }

    /**
     * 根据分组id查询分组关系
     *
     * @param request
     * @return
     */
    @Override
    public Pager<GroupRelation> findAllByGroupId(GetGroupRelationPagerRequest request) {
        request.webParamConvert();
        List<GroupRelation> groupRelationList = groupRelationExtendMapper.findAllByGroupId(request);
        int totalCount = groupRelationExtendMapper.findAllByGroupIdCount(request);
        Pager<GroupRelation> pager = new Pager<>();
        pager.setPageNumber(request.getPageNumber());
        pager.setPageSize(request.getPageSize());
        pager.setList(groupRelationList);
        pager.setTotalCount(totalCount);
        return pager;
    }

    @Override
    public List<Long> findGroupIds(Long userId) {
        return groupRelationExtendMapper.findGroupIdsByUserId(userId);
    }

    @Override
    public List<Long> findGroupIds(Long userId, Set<Long> organizationIds) {
        if (organizationIds.isEmpty()) {
            return findGroupIds(userId);
        }
        return groupRelationExtendMapper.findGroupIds(userId, organizationIds);
    }

    /**
     * 添加组织机构 分组关系
     *
     * @param groupId
     * @param organizationIds
     */
    public void appendRelation(Long groupId, Long[] organizationIds) {
        if (ArrayUtils.isEmpty(organizationIds)) {
            return;
        }
        for (Long organizationId : organizationIds) {
            if (organizationId == null) {
                continue;
            }
            GroupRelation r = getByGroupIdAndOrganizationId(groupId, organizationId);
            if (r == null) {
                r = new GroupRelation();
                r.setGroupId(groupId);
                r.setOrganizationId(organizationId);
                save(r);
            }
        }
    }

    /**
     * 查询分组关系
     *
     * @param groupId
     * @param organizationId
     * @return
     */
    @Override
    public GroupRelation getByGroupIdAndOrganizationId(Long groupId, Long organizationId) {
        GroupRelationExample example = new GroupRelationExample();
        example.or().andGroupIdEqualTo(groupId).andOrganizationIdEqualTo(organizationId);
        List<GroupRelation> groupRelationList = groupRelationExtendMapper.selectByExample(example);
        if (groupRelationList.isEmpty())
            return null;
        return groupRelationList.get(0);
    }


    public void appendRelation(Long groupId, Long[] userIds, Long[] startUserIds, Long[] endUserIds) {
        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(startUserIds)) {
            return;
        }
        if (!ArrayUtils.isEmpty(userIds)) {
            for (Long userId : userIds) {
                if (userId == null) {
                    continue;
                }
                GroupRelation r = getByGroupIdAndOrganizationId(groupId, userId);
                if (r == null) {
                    r = new GroupRelation();
                    r.setGroupId(groupId);
                    r.setUserId(userId);
                    save(r);
                }
            }
        }

        if (!ArrayUtils.isEmpty(startUserIds)) {
            for (int i = 0, l = startUserIds.length; i < l; i++) {
                Long startUserId = startUserIds[i];
                Long endUserId = endUserIds[i];
                //范围查 如果在指定范围内 就没必要再新增一个 如当前是[10,20] 如果数据库有[9,21]
                GroupRelation r = findByGroupIdAndStartUserIdLessThanEqualAndEndUserIdGreaterThanEqual(groupId, startUserId, endUserId);

                if (r == null) {
                    //删除范围内的
                    deleteInRange(startUserId, endUserId);
                    r = new GroupRelation();
                    r.setGroupId(groupId);
                    r.setStartUserId(startUserId);
                    r.setEndUserId(endUserId);
                    save(r);
                }

            }
        }
    }

    /**
     * 删除分组关系
     *
     * @param id
     */
    @Override
    public void delete(Long id) {
        groupRelationExtendMapper.deleteByPrimaryKey(id);
    }

    /**
     * 批量删除分组关系
     *
     * @param ids
     */
    @Override
    public void delete(Long[] ids) {
        if (!ArrayUtils.isEmpty(ids)) {
            for (int i = 0;i < ids.length; i++) {
                delete(ids[i]);
            }
        }
    }

    // @Query("delete from GroupRelation where (startUserId>=?1 and endUserId<=?2) or (userId>=?1 and userId<=?2)")
    private void deleteInRange(Long startUserId, Long endUserId) {
        GroupRelationExample example = new GroupRelationExample();
        example.or().andStartUserIdGreaterThanOrEqualTo(startUserId).andStartUserIdLessThanOrEqualTo(endUserId);
        example.or().andUserIdGreaterThanOrEqualTo(startUserId).andStartUserIdLessThanOrEqualTo(endUserId);
        groupRelationExtendMapper.deleteByExample(example);
    }

    private GroupRelation findByGroupIdAndStartUserIdLessThanEqualAndEndUserIdGreaterThanEqual(Long groupId, Long startUserId, Long endUserId) {
        GroupRelationExample example = new GroupRelationExample();
        example.or().andGroupIdEqualTo(groupId).
                andStartUserIdGreaterThanOrEqualTo(startUserId).andStartUserIdLessThanOrEqualTo(endUserId);

        List<GroupRelation> groupRelationList = groupRelationExtendMapper.selectByExample(example);
        if (groupRelationList.isEmpty())
            return null;
        return groupRelationList.get(0);
    }
    /**
     * 根据分组名获取该分组下的用户
     *
     * @param groupName
     * @return
     */
    @Override
    public List<Long> getUserIdsByGroupName(String groupName){
        return groupRelationExtendMapper.getUserIdsByGroupName(groupName);
    }

    /**
     * 根據組id查找用戶
     *
     * @param groupId
     */
    @Override
    public List<Long> findUserIdsByGroupId(Long groupId) {
        List<Long> userIds = Lists.newArrayList();
        GroupRelationExample example = new GroupRelationExample();
        example.or().andGroupIdEqualTo(groupId);
        List<GroupRelation> groupRelationList = groupRelationExtendMapper.selectByExample(example);
        for (GroupRelation groupRelation:groupRelationList) {
            userIds.add(groupRelation.getUserId());
        }
        return userIds;
    }

    /**
     * 根据用户id查找组Ids
     *
     * @param userId
     */
    @Override
    public List<Long> findGroupIdsByUserId(Long userId) {
        List<Long> groupIds = Lists.newArrayList();
        GroupRelationExample example = new GroupRelationExample();
        example.or().andUserIdEqualTo(userId);
        List<GroupRelation> groupRelationList = groupRelationExtendMapper.selectByExample(example);
        if(groupRelationList!=null && groupRelationList.size()>0){
            for (GroupRelation groupRelation:groupRelationList) {
                groupIds.add(groupRelation.getGroupId());
            }
        }
        return groupIds;
    }
}
